package com.sleet.yuemiao.service.impl;

import com.alibaba.fastjson.JSON;
import com.sleet.yuemiao.YuemiaoApplication;
import com.sleet.yuemiao.comment.YuMiaoComment;
import com.sleet.yuemiao.pojo.PageDto;
import com.sleet.yuemiao.util.HttpUtil;
import com.sleet.yuemiao.util.JsonUtil;
import freemarker.core.TemplateDateFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: yuemiao
 * @ClassName MainService
 * @description:
 * @author: Liyongxing
 * @create: 2021-11-23 19:28
 **/
@Service
@Slf4j
@Order(1000)
public class MainService {

    @Value("${even.zftsl}")
    String zftsl;
    @Value("${even.Cookie}")
    String cookie;
    @Value("${yuemaio.yuemaio}")
    private String hospitalIds;
    @Resource
    YuMiaoComment yuMiaoComment;




    public Object Save20(){

        String birthday="1995-02-07";
        String tel="18805311001";
        String sex =  "1";
        String cname = "红一";
        String idcard="530103199001010016";
        String mxid="dFD_ANiKAAAdZjQB";
        String date="2021-12-29";
        String pid="62";
        Map<String,String> parm = new HashMap<>();

        String curl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=Save20" +
                "&birthday=%s" +
                "&tel=%s" +
                "&sex=%s" +
                "&cname=%s" +
                "&doctype=1" +
                "&idcard=%s" +
                "&mxid=%s" +
                "&date=%s" +
                "&pid=%s" +
                "&Ftime=1&guid=";
        curl = String.format(curl,birthday,tel,sex,cname,idcard,mxid,date,pid);
        String response = HttpUtil.request(null,curl,
                HttpUtil.METHOD_POST,
                parm, HttpUtil.PARAM_TYPE_JSON,getCommonHeader().toArray(new BasicHeader[0]),null
        );
        return response;
    }


    /**
     * 获取某个地区的 医院列表
     * @return
     */
    public Object yuemiao(){
        Map<String,String> parm = new HashMap<>();
        //昆明医院列表路径
        String Kurl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=CustomerList&city=%5B%22%E4%BA%91%E5%8D%97%E7%9C%81%22%2C%22%E6%98%86%E6%98%8E%E5%B8%82%22%2C%22%22%5D&lat=25.0453&lng=102.70973&id=0&cityCode=530100&product=0";
        //重庆医院李列表路径
        String curl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=CustomerList&city=%5B%22%E9%87%8D%E5%BA%86%E5%B8%82%22%2C%22%E9%87%8D%E5%BA%86%E5%B8%82%22%2C%22%22%5D&lat=25.11624&lng=102.75205&id=0&cityCode=500000&product=0";
        String response = HttpUtil.request(null,curl,
                HttpUtil.METHOD_POST,
                parm, HttpUtil.PARAM_TYPE_JSON,getCommonHeader().toArray(new BasicHeader[0]),null
                );
        Map<Object, Object> objectObjectMap = JsonUtil.toMap(response);
        //医院列表
        Object list = objectObjectMap.get("list");
        List<Map<String, Object>> lists = JsonUtil.toList(list);
        //解析医院数据进入医院 初始化医院
        this.parseHospital(lists);
        List<Map<String, Object>> volidHospitals=(List<Map<String, Object>> ) yuMiaoComment.getComment().get("volidHospitals");
        log.info("筛选后的有效医院列表【{}】",volidHospitals);
        //根据所选医院 查询疫苗列表
        List<List<Map<String, Object>>> validYimiaos = new ArrayList<>();
        for (Map<String, Object> volidHospital:volidHospitals){
            String  id = volidHospital.get("id").toString();
            String  lat = volidHospital.get("lat").toString();
            String  lng = volidHospital.get("lng").toString();
            String  cname = volidHospital.get("cname").toString();
            //获取可预约的疫苗
            List<Map<String, Object>> validYimiao = ( List<Map<String, Object>>) this.selectValidTimeByCid(id, lat, lng,cname);
            log.info("可以预约的疫苗列表{}",validYimiao);
            validYimiaos.add(validYimiao);
        }
//        List<List<Map<String, Object>>> validTime = this.getValidTime(validYimiaos);
//        log.info("可以预约的 时间列表[{}]",validTime);
//        yuMiaoComment.getComment().put("validTime",validTime);
        return yuMiaoComment;
    }

    /**
     * 获取疫苗的可以预约的有效时间
     * @param selectValidTimeByCids
     */
    private List<List<Map<String, Object>>> getValidTime(List<Map<String, Object>> selectValidTimeByCids) {
        String month = DateFormatUtils.format(new Date(), "yyyyMM");
       List<List<Map<String, Object>>> validTimeList = new ArrayList<>();
        Map<String,String> parm = new HashMap<>();
        if(!CollectionUtils.isEmpty(selectValidTimeByCids)){
            //根据疫苗获取可预约的时间
                List<Map<String, Object>> validTimes = new ArrayList<>();
                for (Map<String, Object> valid:selectValidTimeByCids){
                    String  pid = valid.get("id").toString();
                    String  id = valid.get("cid").toString();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String validTimeUrl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetCustSubscribeDateAll&pid="+pid+"&id="+id+"&month="+month;//202112
                    String validTimeReponse = HttpUtil.request(null,validTimeUrl,
                            HttpUtil.METHOD_POST,
                            parm, HttpUtil.PARAM_TYPE_JSON,getCommonHeader().toArray(new BasicHeader[0]),null
                    );
                    Map<Object, Object> response = JsonUtil.toMap(validTimeReponse);
                    Object validTimeObj = response.get("list");
                    validTimes = JsonUtil.toList(validTimeObj)
                        .stream().map(obj ->{
                        obj.put("cname",valid.get("cname"));
                        obj.put("text",valid.get("text"));
                        obj.put("id",id);
                        obj.put("pid",pid);
                        return obj;
                    }).collect(Collectors.toList());
                    validTimeList.add(validTimes);
                }
        }
        List<List<Map<String, Object>>> rsvalidTimeList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(validTimeList)){
            for (List<Map<String, Object>> validTimes:validTimeList){
                if(!CollectionUtils.isEmpty(validTimes)){
                    List<Map<String, Object>> collect = validTimes.stream().filter(obj -> {
                        return "true".equals(obj.get("enable").toString());
                    }).collect(Collectors.toList());
                    rsvalidTimeList.add(collect);
                }
            }
        }
        return rsvalidTimeList;
    }

    /**
     * 点击某一个具体的医院时 根据id 选择具体的医院
     *      * @return 可以预约九价的疫苗列表
     * @param id 医院id
     * @param lat 经纬度
     * @param lng
     * @param cname  医院名称 可以为空
     * @return 返回疫苗列表
     */
    public Object selectValidTimeByCid(String id,String lat,String lng,String cname){
        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=CustomerProduct&id=%s&lat=%s&lng=%s";
        String fUrl = String.format(url, id, lat, lng);
        Map<String,String> parm = new HashMap<>();
        String request = HttpUtil.request(null,fUrl,
                HttpUtil.METHOD_POST,
                parm, HttpUtil.PARAM_TYPE_JSON,getCommonHeader().toArray(new BasicHeader[0]),null
        );
        Map<Object, Object> objectObjectMap = JsonUtil.toMap(request);
        //疫苗列表
        Object list = objectObjectMap.get("list");
        //获得疫苗列表
        List<Map<String, Object>> list1 = JsonUtil.toList(list);
        List<Map<String, Object>> valids = list1.stream().filter(item -> {
            //插入医院id 备用
            item.put("cid",id);
            item.put("cname",cname);
            //TODO  换位 九价
//            return "立即预约".equals(item.get("BtnLable").toString()) && "九价人乳头瘤病毒疫苗".equals(item.get("text").toString());
            return "立即预约".equals(item.get("BtnLable").toString());
        }).collect(Collectors.toList());

        return this.getValidTime(valids);
    }



    /**
     * 解析医院数据进入医院
     * @param hospitals 医院列表数据
     */
    private void parseHospital(List<Map<String, Object>> hospitals) {
        List<Map<String, Object>> volidHospitals = new ArrayList<>();
        Assert.notNull(hospitals, "该地区没有有效的医院列表");
        if (!StringUtils.isEmpty(hospitalIds)) {
            String[] split = hospitalIds.split(",");
            for (Map<String, Object> hospital : hospitals) {
                for (String id : split) {
                    if (id.equals(hospital.get("id")) || id.equals(hospital.get("id")+"")) {
                        volidHospitals.add(hospital);
                    }
                }

            }
        }
        yuMiaoComment.getComment().put("volidHospitals",volidHospitals);
    }

    /**
     * 根据医院可以预约的时间 活的疫苗数
     * @return
     */
    public Object GetCustSubscribeDateDetail() {
        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetCustSubscribeDateDetail" +
                "&pid=%s&id=%s&scdate=%s";
        String fUrl = String.format(url, "62", "1885", "2021-12-29");
        Map<String,String> parm = new HashMap<>();
        String response = HttpUtil.request(null,fUrl,
                HttpUtil.METHOD_POST,
                parm, HttpUtil.PARAM_TYPE_JSON,getCommonHeader().toArray(new BasicHeader[0]),null
        );
       return response;
    }

    /**
     * 生成header
     * @return
     */
    private List<Header> getCommonHeader(){
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat"));
        headers.add(new BasicHeader("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html"));
        headers.add(new BasicHeader("zftsl", zftsl));
        headers.add(new BasicHeader("Accept","application/json, text/plain, */*"));
        headers.add(new BasicHeader("Host","cloud.cn2030.com"));
        headers.add(new BasicHeader("Accept-Encoding","gzip, deflate, br"));
        headers.add(new BasicHeader("Cookie", cookie));
        return headers;
    }


    //    /**
//     * 授权获得sessionId
//     * @return
//     */
//    public Object auth(){
//        Map<String,String> parm = new HashMap<>();
//        String curl = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=auth&code="+code;
//        String response = HttpUtil.request(null,curl,
//                HttpUtil.METHOD_POST,
//                parm, HttpUtil.PARAM_TYPE_JSON,getCommonHeader().toArray(new BasicHeader[0]),null
//        );
//
//        Map<Object, Object> objectObjectMap = JsonUtil.toMap(response);
//        cookie = objectObjectMap.get("sessionId").toString();
//        yuMiaoComment.getComment().put("Cookie",cookie);
//        return yuMiaoComment;
//    }
}
